package logic

import (
	"context"
	"encoding/hex"

	"charging_pile/devices/internal/svc"
	"charging_pile/devices/pb"
	iot "charging_pile/util"
	"charging_pile/util/protocol/jiuxing"

	"github.com/zeromicro/go-zero/core/logx"
)

type StartChargeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewStartChargeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StartChargeLogic {
	return &StartChargeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 启动充电
func (l *StartChargeLogic) StartCharge(in *pb.StartChargeReq) (*pb.StartChargeResp, error) {
	// todo: add your logic here and delete this line
	// jxpkg := ConvertRpc2JxPkg(in)
	// ch := l.svcCtx.Mq.SendMsgWaitAck(jxpkg)
	// select {
	// case <-ch:
	// case <-time.After(time.Second * 5):
	// }
	// close(ch)

	return &pb.StartChargeResp{}, nil
}

func ConvertRpc2JxPkg(in *pb.StartChargeReq) *jiuxing.Package {

	pl := jiuxing.Msg1F{
		Tm:         iot.FormatJxTime(),
		Plug:       0,
		Order:      in.Order,
		UserID:     in.User,
		UserType:   2,
		GroupCode:  in.OrgCode,
		CtlMode:    4,
		CtlParam:   0,
		ChargeMode: 1,
		StartMode:  1,
		StartTime:  iot.FormatJxTime(),
		OptCode:    "",
		BillMode:   1,
	}
	p := pl.Encode()
	sn, _ := hex.DecodeString(in.Pile)
	pkg := &jiuxing.Package{
		Cmd:        0x1F,
		Sn:         sn,
		Encryption: 1,
		PackageLen: uint16(len(p)),
		Payload:    p,
		Check:      0,
	}

	return pkg
}
